package ForkJoin框架.RecursiveTask;

import java.util.concurrent.*;

// 计算 left 到 right 的和
public class Count extends RecursiveTask<Integer> {
    int threshhold = 100;
    int left;
    int right;

    public Count(int left, int right) {
        this.left = left;
        this.right = right;
    }

    @Override
    protected Integer compute() {
        int res = 0;
        if (right - left < threshhold)
            for (int i = left; i <= right; i++)
                res += i;
        else {
            int middle = left + (right - left) / 2;

            Count leftTask = new Count(left, middle);
            leftTask.fork();// 执行compute方法
            Integer lRes = leftTask.join();

            Count rightTask = new Count(middle + 1, right);
            rightTask.fork();// 执行compute方法
            Integer rRes = rightTask.join();

            res = lRes + rRes;
        }
        return res;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        // ForkJoinPool 是线程池
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        Count count = new Count(1, 3);
        ForkJoinTask<Integer> submit = forkJoinPool.submit(count);
        System.out.println(submit.get());// 6

    }
}
